﻿using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using CKS.EBE.API;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace CKS.EBE.WebControls
{
	/// <summary>
	/// Generate a link to the rss feed, or a rss feed autodiscovery link for the page head
	/// </summary>
	public class RSS : SPControl
	{
		public enum Mode
		{
			LinkToRSSFeed,
			RSSAutoDiscoveryLink
		}

		/// <summary>
		/// Set to LinkToRSSFeed (RSS Link with icon) or RSSAutoDiscoveryLink (finding the RSS feed for posts in the head)
		/// </summary>
		public Mode ControlMode { get; set; }

		/// <summary>
		/// get the custom rss feed url if not empty, or the default rss feed url
		/// </summary>
		public string RssFeedUrl
		{
			get
			{
				return string.IsNullOrEmpty(BlogContext.Current.Settings.CustomRSSFeedUrl) ?
					 string.Format("{0}/rss.xml", SPContext.Current.Web.Url) :
					 BlogContext.Current.Settings.CustomRSSFeedUrl;
			}
		}

		/// <summary>
		/// get the relative rss feed icon url (e.g. /Themes/Default/images/RSS.png)
		/// </summary>
		public string ImageUrl
		{
			get
			{
				string theme = BlogContext.Current.BlogTheme;
				string imageUrl = string.Format("/Themes/{0}/images/RSS.png", theme);

				string relativeURL;
				if (BlogContext.Current.Settings.UseSiteCollectionThemes)
				{
					relativeURL = SPContext.Current.Site.RootWeb.ServerRelativeUrl;
				}
				else
				{
					relativeURL = SPContext.Current.Web.ServerRelativeUrl;
				}

				if (relativeURL != "/")
				{
					// add server realtive url if not "/"
					imageUrl = relativeURL + imageUrl;
				}

				return imageUrl;
			}
		}

		/// <summary>
		/// this text will be shown next to the RSS feed item in the link
		/// </summary>
		public string LinkText { get; set; }

		protected override void CreateChildControls()
		{
			base.CreateChildControls();

			switch (ControlMode)
			{
				case Mode.LinkToRSSFeed:
					var hyperlink = new HtmlGenericControl("a") { ID = "rss" };
					hyperlink.Attributes.Add("href", RssFeedUrl);
					hyperlink.Controls.Add(new Image { AlternateText = LinkText, ImageUrl = ImageUrl, BorderStyle = BorderStyle.None });
					hyperlink.Controls.Add(new Label { Text = LinkText });
					Controls.Add(hyperlink);
					break;
				case Mode.RSSAutoDiscoveryLink:
					string postsListName = Localization.GetResource("Posts");
					var link = new HtmlGenericControl("link");
					link.Attributes.Add("rel", "alternate");
					link.Attributes.Add("type", "application/rss+xml");
					link.Attributes.Add("title", postsListName);
					link.Attributes.Add("href", RssFeedUrl);
					Controls.Add(link);
					break;
			}
		}
	}
}